<template>
  <div>

    <my-form-drawer :title="title" :width="450" :visible="visible" @ok="edit" @cancel="onClose">
      <a-form-model ref="form" :model="form" :rules="rules">
        <a-form-model-item label="检测规则" prop="auditRule">
          <a-select default-value="1" style="width: 150px" v-model="form.ruleId" placeholder="检测规则">
            <a-select-option :value="item.id" v-for="(item, key) in ruleData" :key="key">
              {{ item.ruleName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="文件地址" prop="auditFilePath">

          <template>

            <a-upload
                ref="batchUploadRef"
                :accept="uploadAccept"
                :multiple="true"
                :headers="headers"
                :action="uploadAction"
                list-type="picture-card"
                :before-upload="beforeUpload"
                @change="handleUploadChange"
                :show-upload-list="{ showPreviewIcon: false, showRemoveIcon: true }"
            >
              <div>
                <a-icon type="plus"/>

              </div>
            </a-upload>
          </template>
        </a-form-model-item>
        <br/>
        <div v-show="form.taskType == 'bigFile'" class="remind1">
          <span style="color: rgba(0, 0, 0, 0.71)">
            <a-icon type="info-circle" style="color: red; margin-right: 5px"/>
            若文件中存在公式、复杂表格等内容，可能会影响检测准确率；建议对该部分检测结果进行复核，如有疑问，请联系管理人员</span
          >
        </div>
        <div v-show="form.taskType == 'audio'" class="remind2">
          <span style="color: rgba(0, 0, 0, 0.71)"
          ><a-icon type="info-circle" style="color: red; margin-right: 5px"/>
            音频质量可能影响检测结果，为提高语音检测准确率，请上传质量较高的音频进行检测；如有疑问，请联系管理人员</span
          >
        </div>
      </a-form-model>
    </my-form-drawer>
    <upload-notice ref="UploadNotice"/>
  </div>
</template>

<script>
  import MyFormDrawer from '@/components/drawer/MyFormDrawer';
  import UploadNotice from '@/pages/verify/components/UploadNotice.vue';
  import {rule} from '@/utils/validateRules';
  import {uploadBatch} from '../../services/verify';
  import {list} from '@/services/checkRule';
  import Cookie from 'js-cookie';
  import {generateTaskName, getAUploadAccept} from "../../utils/util";

  export default {
    name: 'VerifyBatchUpload',
    components: {MyFormDrawer, UploadNotice},
    data() {
      return {
        uploadAction: '', //文件上传地址
        baseOssUrl: process.env.VUE_APP_OSS_BASE_URL,
        headers: {
          Authorization: Cookie.get('Authorization'),
        },
        uploadAccept: '', //支持文件格式
        title: '',
        form: {
          taskType: '',
          ruleId: '1',
          taskName: '',
          auditFilePath: '',
        },
        fileList: [],
        visible: false,
        rules: {
          word: [
            {required: true, message: '敏感词不能为空', trigger: 'taskName'},
            {validator: rule.checkSpace, message: '敏感词不能为空', trigger: 'blur'},
          ],
        },
      };
    },
    created() {
      this.ruleList();
    },
    methods: {
      permission(name) {
        let permissions = this.$store.getters['account/permissions'];
        return permissions.filter((m) => m.id == name || m.operation.indexOf(name) >= 0).length > 0;
      },
      ruleData: [],
      initData() {
        this.form = {
          auditFilePath: '',
        };
      },
      //video image audio bigFile
      //视频 图片 音频 图文
      changeForm(state, taskType, ruleId) {
        this.uploadAction = '/api/verify/saveFile?taskType='+ taskType;
        this.uploadAccept = getAUploadAccept(taskType);
        //清空历史图片
        this.$refs['batchUploadRef'].sFileList = []
        this.fileList = []
        this.form.ruleId = ruleId;
        this.form.taskType = taskType;
        this.visible = state;
        this.title = '批量上传文件';
      },
      beforeUpload(file) {
        let fileSize = file.size / (1024 * 1024);
        //文件大小超过最大值
        if (fileSize >= 1024) {
          this.$message.error(`目前仅支持小于1G的文件上传审核`);
          return;
        }
      },
      handleUploadChange: function (info) {
        if (info.file.status === 'uploading') {
          return;
        }
        if (info.file.status === 'done' ) {
          if(info.file.response.code === 0){
            this.$message.success(`上传成功`);
            let auditFilePath = info.file.response.data;
            let fullPath = this.baseOssUrl + auditFilePath;
            this.fileList.push(
                {
                  uid: info.file.uid,
                  name: info.file.name,
                  auditFilePath: auditFilePath,
                  url: fullPath,
                  thumbUrl: fullPath
                }
            );
          }else {
            this.$message.error(info.file.response.message);
            //移除
            this.$refs['batchUploadRef'].sFileList  = this.$refs['batchUploadRef'].sFileList.filter(function(item) {
              return item.uid !== info.file.uid
            });
          }

        } else if (info.file.status === 'removed') {
          //移除
          this.fileList = this.fileList.filter(function(item) {
            return item.uid !== info.file.uid
          });
        } else if (info.file.status === 'error') {
          this.$message.error(`上传失败`);
        }
      },
      onClose() {
        this.visible = false;
        this.$refs['form'].clearValidate();
        this.initData();
      },
      ruleList() {
        list().then((res) => {
          if (res.data.code === 0) {
            this.ruleData = res.data.data;
            console.log(this.ruleData, res.data);
          }
        });
      },
      edit() {
        if (this.fileList == null || this.fileList.length == 0) {
          this.$message.error(`请上传文件`);
          return;
        }
        let uploadTaskList = [];
        this.fileList.forEach(item => {
          let taskName = generateTaskName(item.name, this.form.taskType);
          uploadTaskList.push({
            ruleId: this.form.ruleId,
            auditFilePath: item.auditFilePath,
            taskType: this.form.taskType,
            taskName: taskName,
          })
        })

        uploadBatch(uploadTaskList).then((res) => {
          if (res.data.code === 0) {
            this.$message.success('上传成功');
            if (this.form.taskType == 'audio' || this.form.taskType == 'bigFile' || this.form.taskType == 'video') {
              this.$refs.UploadNotice.show(true, this.form.taskType);
            }
            this.onClose();
            this.$emit('getList');
          }
        });
      },
    },
  };
</script>

<style lang="less" scoped>
  .remind1 {
    width: 410px;
    height: 90px;
    background: rgba(169, 180, 206, 0.14);
    border-radius: 7px 7px 7px 7px;
    opacity: 1;
    padding: 12px 15px 0 15px;
  }

  .remind2 {
    width: 410px;
    height: 70px;
    background: rgba(169, 180, 206, 0.14);
    border-radius: 7px 7px 7px 7px;
    opacity: 1;
    padding: 12px 15px 0 15px;
  }

  //上传
  /deep/ .ant-upload-list {
    display: block !important;
  }


</style>
